package com.rpp.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author peng
 * @Date 2020/10/28 10:45 上午
 */
@Configuration
public class RabbitMqConfig {

    /**
     * 订单消息队列
     *
     * @return
     */
    @Bean
    public Queue queueTTLWaiting() {
        Map<String, Object> props = new HashMap<>();
        // 设置该队列中的消息过期时间为5分钟
        props.put("x-message-ttl", 1 * 60 * 1000);
        // 设置该队列所关联的死信交换器(当队列消息TTL到期后依然没有消费，则加入死信队列)
        props.put("x-dead-letter-exchange", "ex.order.dlx");
        // 设置该队列所关联的死信交换器的routingKey，如果没有特殊指定，使用原 队列的routingKey
        props.put("x-dead-letter-routing-key", "order.dlx");
        return new Queue("q.order.ttl-waiting", true, false, false, props);
    }

    /**
     * 订单消息交换器
     *
     * @return
     */
    @Bean
    public Exchange exchangeTTLWaiting() {
        return new DirectExchange("ex.order.ttl-waiting", true, false);
    }

    /**
     * 订单消息队列绑定交换器
     *
     * @return
     */
    @Bean
    public Binding bindingTTLWaiting() {
        return BindingBuilder.bind(queueTTLWaiting()).to(exchangeTTLWaiting()).with("order.ttl-waiting").noargs();
    }

    /**
     * 死信队列
     *
     * @return
     */
    @Bean
    public Queue queueDlx() {
        return new Queue("q.order.dlx", true, false, false);
    }

    /**
     * 死信交换器
     */
    @Bean
    public Exchange exchangeDlx() {
        return new DirectExchange("ex.order.dlx", true, false, null);
    }

    /**
     * 死信交换器绑定死信队列
     */
    @Bean
    public Binding bindingDlx() {
        return BindingBuilder.bind(queueDlx()).to(exchangeDlx()).with("order.dlx").noargs();
    }
}
